package org.jiangy.usercenter;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jiangy.authentication.DefaultGrantedAuthority;
import org.jiangy.usercenter.entity.Customer;
import org.jiangy.usercenter.entity.Staff;
import org.jiangy.usercenter.entity.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 * 用户详情代理，适配 SpringSecurity UserDetails 与业务系统用户
 * <p>创建时间: 2024/8/13 </p>
 *
 * @author <a href="mailto:jiangliu0316@outlook.com" rel="nofollow">蒋勇</a>
 */
@Deprecated
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDetailsProxy<T extends User> implements UserDetails {

    private T delegate;

    public UserDetailsProxy(T user) {
        this.delegate = user;
    }

    @JsonIgnore
    @Override
    public Collection<DefaultGrantedAuthority> getAuthorities() {
        return delegate.getAuthorities();
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return delegate.getPassword();
    }

    @JsonIgnore
    @Override
    public String getUsername() {
        return delegate.getUsername();
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return delegate.isEnabled();
    }

    @SuppressWarnings("unchecked")
    public static <T extends User> UserDetailsProxy<T> create(String json) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        // 设置忽略未知属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonNode rootNode = mapper.readTree(json);
        String classType = rootNode.get("delegate").get("classType").asText();

        if (Customer.class.getTypeName().equals(classType)) {
            return (UserDetailsProxy<T>) mapper.readValue(json, new TypeReference<UserDetailsProxy<Customer>>() {
            });
        } else if (Staff.class.getTypeName().equals(classType)) {
            return (UserDetailsProxy<T>) mapper.readValue(json, new TypeReference<UserDetailsProxy<Staff>>() {
            });
        }
        // 处理其他情况或抛出异常
        throw new IllegalArgumentException("Unknown user type: " + classType);
    }
}
